package juc.design.guardedObject;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j(topic = "c.TestGuardedObject")
public class TestGuardedObject {
    public static void main(String[] args) {
        GuardedObject guardedObject = new GuardedObject();
        new Thread(() -> {
            //向response中填充数据
            List<String> response = new ArrayList<>();
            response.add("aa");
            response.add("bb");
            response.add("cc");
            log.debug("complete...");

            //任务完成，通知等待中的线程t1
            guardedObject.complete(response);
        }).start();

        log.debug("waiting...");

        //获取response并打印出来
        Object response = guardedObject.get();
        log.debug("get response: [{}] lines", response);

    }

}
class GuardedObject {

    private Object response;
    private final Object lock = new Object();

    public Object get() {
        synchronized (lock) {
            // 条件不满足则等待
            while (response == null) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return response;
        }
    }

    public void complete(Object response) {
        synchronized (lock) {
            // 条件满足，通知等待线程
            this.response = response;
            lock.notifyAll();
        }
    }
}